package com.qingyun.form.internal

import com.qingyun.form.items.BaseFormItem

internal class FormItemList : Iterable<BaseFormItem> {
    /**
     * 原始数据列表
     */
    private val items = mutableListOf<BaseFormItem>()

    val size: Int
        get() = items.size

    override fun iterator(): Iterator<BaseFormItem> {
        return items.iterator()
    }

    fun add(item: BaseFormItem): Boolean {
        return add(-1, item)
    }

    fun add(index: Int, item: BaseFormItem): Boolean {
        if (items.contains(item)) {
            return false
        }
        if (index == -1) {
            return items.add(item)
        }
        items.add(index, item)
        return true
    }

    fun removeAll(set: Set<BaseFormItem>): Boolean {
        return items.removeAll(set)
    }

    fun remove(item: BaseFormItem): Boolean {
        return items.remove(item)
    }

    fun remove(name: String): Boolean {
        return get(name)?.let { remove(it) } == true
    }


    operator fun get(position: Int): BaseFormItem {
        return items[position]
    }

    operator fun get(name: String): BaseFormItem? {
        return items.find { it.name == name }
    }

    fun indexOf(item: BaseFormItem): Int {
        return items.indexOf(item)
    }

    /**
     * 查找表单中最后一个子表单的索引
     */
    fun findChildrenIndex(parent: BaseFormItem): Int {
        val parentIndex = items.indexOf(parent)
        //表单组中没有这个父表单
        if (parentIndex < 0) {
            return -1
        }
        //查找子表单的数量
        val childrenCount = items.count { it.parent == parent }
        //最后一个子表单的索引 = 父表单的索引 + 子表单的数量
        return parentIndex + childrenCount
    }

    fun toMap(): Map<String, String> {
        return items.associateBy({ it.name }, { it.value ?: "" })
    }

    fun destroy() {
        items.clear()
    }
}